<template>
  <el-row justify="end">
    <el-col :span="16" style="text-align: left; display: flex;">
       <el-upload
          :show-file-list="false"
          class="upload-demo"
          action="http://localhost:3001/upload"
          :headers="token"
          :on-success="getData"
          multiple
          :limit="1"
        >
            <el-button @click="importData" type="primary">导入数据</el-button>
        </el-upload>
        <el-button @click="addStudent" type="primary" style="margin-left: 20px;">添加学生</el-button>
    </el-col>
    <el-col :span="6">
      <el-input v-model="searchInput" placeholder="请输入内容"></el-input>
    </el-col>
    <el-col :span="2">
      <el-button type="primary" @click="searchData">搜索</el-button>
    </el-col>
  </el-row>
  <el-table
    :data="
      tableData.filter(
        (data) =>
          !search || data.name.toLowerCase().includes(search.toLowerCase())
      )
    "
    :header-cell-style="{background:'#f4f3f9',color:'#606266', fontSize: '12px'}"
    :cell-style = "{fontSize: '12px'}"
    style="width: 100%; margin-top: 10px;"
  >
    <!--
    <el-table-column
      prop="id"
      label="序号"
      width="50">
    </el-table-column>
    -->
    <el-table-column prop="studentId" v-if="false"> </el-table-column>
    <el-table-column label="姓名" prop="studentName" width="80"> </el-table-column>
    <el-table-column label="身份证号" prop="idNum"> </el-table-column>
    <el-table-column label="班级" prop="studentClass"> </el-table-column>
    <el-table-column label="班主任" prop="studentMaster"> </el-table-column>
    <el-table-column label="班主任电话" prop="masterPhone" width="180"> </el-table-column>
    <el-table-column label="预留电话" prop="phoneNum" width="180"> </el-table-column>
    <el-table-column label="操作" align="right">
      <template #default="scope">
          <el-button @click="editUser(scope.row)" size="small" type="primary">编辑</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    small="true"
    background
    layout="prev, pager, next"
    :page-size="5"
    :total="total"
    :current-page="currentPage"
    @current-change="changePage"
    style="margin-top: 30px;">
  </el-pagination>
  <el-drawer
  title="编辑"
  v-model="drawer"
  v-show="drawer"
  :lock-scroll="false"
  :with-header="true">
      <el-form :label-position="labelPosition" label-width="120px" :model="formLabelAlign" ref="ruleFormRef" >
        <el-form-item label="id" v-show="false">
          <el-input v-model="formLabelAlign.studentId"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="studentName">
          <el-input v-model="formLabelAlign.studentName" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idNum">
          <el-input v-model="formLabelAlign.idNum" placeholder="请输入身份证号"></el-input>
        </el-form-item>
        <el-form-item label="班级" prop="studentClass">
          <!--<el-input v-model="formLabelAlign.studentClass"></el-input>-->
          <el-select v-model="formLabelAlign.studentClass" placeholder="请选择班级" style="width: 100%;">
              <el-option
                v-for="item in classList"
                :key="item.studentClass"
                :label="item.studentClass"
                :value="item.studentClass">
              </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班主任" prop="studentMaster">
          <el-input v-model="formLabelAlign.studentMaster" placeholder="请输入班主任"></el-input>
        </el-form-item>
        <el-form-item label="班主任联系方式" prop="masterPhone">
          <el-input v-model="formLabelAlign.masterPhone" placeholder="请输入班主任联系方式"></el-input>
           
        </el-form-item>
        <el-form-item label="预留电话" prop="phoneNum">
          <el-input v-model="formLabelAlign.phoneNum" placeholder="请输入预留电话"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" v-if="ifEdit">保存</el-button>
          <el-button type="primary" @click="onAdd" v-if="!ifEdit">添加</el-button>
          <el-button>重置</el-button>
        </el-form-item>
      </el-form>
  </el-drawer>
</template>
<script>
import {getUser, addUser, updateUser, search, exportFile} from "../api/user.js"
import { getDistrictInfor } from "../api/district.js"
export default {
  data() {
    let checkidNum = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入身份证号'));
        } else {
          let idReg = /^([1-9]\d{5})(19\d{2}|20(0\d|1[0-8]))((0[1-9]|1[0-2]))(([0-2]\d|3[0-1]))\d{3}([\dxX])$/;
          if (idReg.test(value)) {
            callback();
          }
          else {
            callback(new Error('请输入符合格式要求的身份证号'));
          }
        }
    }
    let checkPhone1 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入班主任电话'));
        } else {
          let idReg = /^1[3-9]\d{9}$/;
          if (idReg.test(value)) {
            callback();
          }
          else {
            callback(new Error('班主任电话格式错误'));
          }
        }
    }
    let checkPhone2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入预留电话'));
        } else {
          let idReg = /^1[3-9]\d{9}$/;
          if (idReg.test(value)) {
            callback();
          }
          else {
            callback(new Error('请输入预留电话'));
          }
        }
    }
    return {
      tableData: [
      ],
      search: "",
      drawer: false,
      labelPosition: 'left',
      formLabelAlign: {
        userName: '', 
        cardId: '', 
        address: '', 
        phone: '', 
        subdistrict: '',
        building: '',
        block: '', 
        room: ''
      },
      queryParams: {
        page: 1,
        size: 5
      },
      total: '',
      currentPage: 1,
      searchInput: '',
      token: { authorization: localStorage.getItem("token") },
      ifEdit: false,
      rules: {
          studentName: [
            { required: true, message: '请输姓名', trigger: 'blur' },
            { min: 2, max: 4, message: '长度在 2 到 4 个字符', trigger: 'blur' }
          ],
          idNum: [
            { validator: checkidNum, required: true, trigger: 'blur' }
          ],

          masterPhone: [
            { validator: checkPhone1, trigger: 'blur' }
          ],
          phoneNum: [
            { validator: checkPhone2,  trigger: 'blur' }
          ],
          studentClass: [
            { required: true, message: '请选择班级', trigger: 'blur' }
          ]
      },
      classList: []
    };
  },
  methods: {
    handleEdit(index, row) {
      console.log(index, row);
    },
    getData() {
      this.$message({
          type: 'success',
          message: `导入成功！`
      })
      this.getUserList();
    },
    handleDelete(index, row) {
      console.log(index, row);
    },
    async getUserList() {
      this.queryParams.user = localStorage.getItem("user");
      let result = await getUser(this.queryParams);
      if(result.data.status == 'ok') {
        this.tableData = result.data.userList;
        this.total = result.data.total
        console.log(result.data.total);
      }
    },
    editUser(row) {
      this.ifEdit = true;
      this.formLabelAlign.studentName = row.studentName;
      this.formLabelAlign.idNum = row.idNum;
      this.formLabelAlign.studentClass = row.studentClass;
      this.formLabelAlign.studentMaster = row.studentMaster;
      this.formLabelAlign.masterPhone = row.masterPhone;
      this.formLabelAlign.phoneNum = row.phoneNum;
      this.formLabelAlign.studentId = row.studentId;
      this.drawer = true
    },
    addStudent() {
      this.ifEdit = false;
      this.formLabelAlign.studentName = '';
      this.formLabelAlign.idNum = '';
      this.formLabelAlign.studentClass = '';
      this.formLabelAlign.studentMaster = '';
      this.formLabelAlign.masterPhone = '';
      this.formLabelAlign.phoneNum = '';
      this.formLabelAlign.studentId = '';
      this.drawer = true;
    },
    async onSubmit() {

      let result = await updateUser(this.formLabelAlign);
      if(result.data.status == "ok") {
        this.drawer = false;
        this.getUserList();
      }
    },
    async onAdd() {
      let result = await addUser(this.formLabelAlign);
      if(result.data.status == "ok") {
          this.drawer = false;
          this.getUserList();
      }
    },
    changePage(e) {
      this.currentPage = e;
      this.queryParams.page = e;
      this.getUserList();
    },
    async searchData() {
      let result = await search({'search': this.searchInput});
      if(result.data.status == 'ok') {
        this.tableData = result.data.userList;
      }
    },
    async importData() {

    },
    async exportData() {
      let userName = localStorage.getItem("user");
      let result = await exportFile(userName);
      console.log(result);
    },
    async getDistrictList() {
        this.queryParams.user = localStorage.getItem("user");
        let result = await getDistrictInfor(this.queryParams);
        if(result.data.status == 'ok') {
          this.classList = result.data.districtList;
        }
    }
  },
  mounted() {
    this.getUserList();
    this.getDistrictList();
  }
};
</script>
<style scoped>
</style>